{% load static %}
<link rel="stylesheet" href="{% static 'css/form.css' %}">
<link rel="stylesheet" href="{% static 'css/sweetalert2.css' %}" >
  <div class="container">
    {% if form.instance.pk %}
        <h2>编辑学生信息</h2>
    {% else %}
        <h2>添加学生信息</h2>
    {% endif %}
    <form method="post">
        {% csrf_token %}
        {% for field in form %}
        <div class="form-group">
          <label for="{{ field.id_for_label }}">{{ field.label }}:</label>
              <!-- 如果是老师用户，班级需要单独处理 -->
              {% if field.name == 'grade' %}
              <!-- required 为必填项 -->
                <select name="{{ field.name }}" id="{{ field.id_for_label }}" required>
                    {% if request.session.user_role == 'teacher' %}
                        {% for grade in grades %}
                            <option value="{{ grade.pk }}" selected>{{ grade.grade_name }}</option>
                        {% endfor %}
                    {% else %}  <!-- 如果非老师，则全部展示，学生不用管，因为它访问不了学生管理 -->
                        <option> 请选择班级 </option>
                        {% for grade in grades %}
                            <option value="{{ grade.pk }}">{{ grade.grade_name }}</option>
                        {% endfor %}
                    {% endif %}                   
                </select>
              {% else %}
                  {{ field }}
                  {% if field.help_text %}
                      <small class="form-text text-muted">{{ field.help_text }}</small>
                  {% endif %}
          {% endif %}
      </div>
      {% endfor %}
      <div class="handleButton">
          <button type="submit" id="saveButton">保存</button>
          <button type="button" id="cancelButton" onclick="window.parent.Swal.close();">取消</button>
      </div>
    </form>
</div>

{% if student.pk %}
<script>
  var actionUrl = "{% url 'student_update' student.pk %}";
</script>
{% else %}
  <script>
    var actionUrl = "{% url 'student_create' %}";
  </script>
{% endif %}
<script src="{% static 'js/sweetalert2.js' %}" ></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');
    const url = actionUrl
    form.addEventListener('submit', function(e) {
      e.preventDefault(); // 阻止表单默认提交
      let formData = new FormData(form)
      // 使用fetch发送请求
      fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          'X-CSRFToken': formData.get('csrfmiddlewaretoken'),
        }
      }).then(response => response.json())
      .then(data=> {
        if (data.status === 'success') {
          Swal.fire({
            icon: 'success',
            title: data.messages,
            text: '数据已成功提交'
          }).then((result) => {
            if (result.value) {
              // 刷新父页面
              window.parent.location.reload()
            }
          })
        } else {
            // 解析嵌套的 JSON 字符串
            const errors = JSON.parse(data.messages);
            // 构造错误信息的文本
            let errorMessage = '';
            for (const field in errors) {
                if (errors.hasOwnProperty(field)) {
                    errors[field].forEach(error => {
                        errorMessage += `<li style="color:red;text-align:left;margin-left: 100px;"> ${error.message} </li>`;
                    });
                }
            }
            // 使用 SweetAlert2 显示错误信息
            Swal.fire({
                icon: 'error',
                title: '提交错误',
                html: errorMessage,
                confirmButtonText: '关闭'
            });
        }

      }).catch(error => {
        Swal.fire({
          icon: 'error',
          title: '网络请求失败',
          text: '无法连接到服务器，请稍后再试',
          confirmButtonText: '关闭'
        })
      })
    })
    

  })


</script>